﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication14
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string name = TextBox1.Text;
            string pwd = TextBox2.Text;
            //第一步：新建连接对象
            SqlConnection connection = new SqlConnection();
            //第二步：给连接对象指定连接的参数（连接字符串）
            connection.ConnectionString = "Data Source = localhost; Initial Catalog = Student; Integrated Security = SSPI;";
            //第三步：开始建立连接
            connection.Open();//Open函数用于打开数据库连接
            //第四步：输出提示
            if (connection.State == System.Data.ConnectionState.Open)
            {
                Response.Write("<script>alert('数据库连接成功！');</script>");
            }
            else
            {
                Response.Write("<script>alert('数据库连接失败！');</script>");
            }
            //注入
            string sql = "select * from zm where UserName=@name and Password=@pwd";
            SqlParameter[] pars =
            {
                new SqlParameter("@name",name),
                new SqlParameter("@pwd",pwd)
            };

            SqlCommand cmd = new SqlCommand(sql,connection);
            cmd.Parameters.AddRange(pars);

            //数据读取器
            SqlDataReader sdr = cmd.ExecuteReader();//查询
            if (sdr.Read())
            {
                Session["CurrentUserName"] = name;
                Response.Redirect("WebForm1.aspx");
            }
            else
            {
                Literal1.Text = "登录失败！";
            }

        }
    }
}